import django_filters
from django.db.models import Q

from goods.models import Goods


class GoodsFilter(django_filters.rest_framework.FilterSet):
    """
    商品的过滤类
    """
    price_min = django_filters.NumberFilter(field_name="shop_price", lookup_expr='gte')
    price_max = django_filters.NumberFilter(field_name="shop_price", lookup_expr='lte')
    # 自定义过滤函数
    top_category = django_filters.NumberFilter(method='top_category_filter', label="最热商品类别")

    def top_category_filter(self, queryset, name, value):
        queryset = queryset.filter(Q(category_id=value) | Q(category__parent_category_id=value) | Q(
            category__parent_category_id__parent_category_id=value))
        return queryset

    class Meta:
        model = Goods
        fields = ['price_min', 'price_max', 'top_category', 'is_hot', 'is_new']
